<?php
  /**
   * Elgg europass : Edit action
   * 
   * @package ElggEuropass
   * @link http://e-portfolio.uvsq.fr/
   */

  // Make sure we're logged in (send us to the front page if not)
  // Don't check usual action_gatekeeper(); as this is not a proper action
  gatekeeper();

  // Get input data
  $guid =       (int)get_input('guid');
  $access =     (int)get_input('access_id');
  $tags =       get_input('tags');
  $export =     get_input('export');
  $xmlString =  get_input('EUROPASSCV', '', false);
  
  // Arrayify tag string
  $tagarray =   string_to_tag_array($tags);
    
  // Cache to the session
  $_SESSION['xml'] = $xmlString;
  
  // Save preferences
  if (empty($xmlString) && (is_numeric($access) || !empty($tags)))
  {
    $europass = get_entity($guid);

    // Make sure we have permission to edit
    if ($europass->getSubtype() == "europass" && $europass->canEdit())
    {
      $europass->access_id = $access;
      
      // Deal with tags
      $europass->clearMetadata('tags');
			if (is_array($tagarray)) {
			  $europass->tags = $tagarray;
			}
      $europass->save();
      
      $europass->export = (!empty($export)) ? true : false;
      forward("pg/europass/" . $owner->username);
    }
  }
  // Save XML CV
  else
  {
    $europass = get_entity($guid);

    // Make sure we actually have permission to edit
    if ($europass->getSubtype() == "europass" && $europass->canEdit())
    {
      $xml = new SimpleXMLElement($xmlString);

      // Get info from XML
      // identification
      $result = $xml->xpath('//europass:learnerinfo/identification/firstname');
      $europass->firstname = fixEncoding($result[0]);
      $result = $xml->xpath('//europass:learnerinfo/identification/lastname');
      $europass->lastname = fixEncoding($result[0]);
      $result = $xml->xpath('//europass:learnerinfo/identification/contactinfo/address/addressLine');
      $europass->addressLine = fixEncoding($result[0]);
      $result = $xml->xpath('//europass:learnerinfo/identification/contactinfo/address/municipality');
      $europass->municipality = fixEncoding($result[0]);
      $result = $xml->xpath('//europass:learnerinfo/identification/contactinfo/address/postalCode');
      $europass->postalCode = $result[0];
      $result = $xml->xpath('//europass:learnerinfo/identification/contactinfo/address/country/code');
      $europass->countryCode = $result[0];
      $result = $xml->xpath('//europass:learnerinfo/identification/contactinfo/address/country/label');
      $europass->countryLabel = fixEncoding($result[0]);
      $result = $xml->xpath('//europass:learnerinfo/identification/contactinfo/telephone');
      $europass->telephone = $result[0];
      $result = $xml->xpath('//europass:learnerinfo/identification/contactinfo/fax');
      $europass->fax = $result[0];
      $result = $xml->xpath('//europass:learnerinfo/identification/contactinfo/mobile');
      $europass->mobile = $result[0];
      $result = $xml->xpath('//europass:learnerinfo/identification/contactinfo/email');
      $europass->email = fixEncoding($result[0]);
      $result = $xml->xpath('//europass:learnerinfo/identification/demographics/birthdate');
      $europass->birthdate = $result[0];
      $result = $xml->xpath('//europass:learnerinfo/identification/demographics/gender');
      $europass->gender = $result[0];
      $result = $xml->xpath('//europass:learnerinfo/identification/demographics/nationality/code');
      $europass->nationality = fixEncoding($result[0]);
      
      // application
      $result = $xml->xpath('//europass:learnerinfo/application/label');
      $europass->application = fixEncoding($result[0]);
      
      // education
      $result = $xml->xpath('//europass:learnerinfo/educationlist/education/title');
      $europass->clearMetadata('educationTitles');
      $europass->educationTitles = fixEncoding($result);
      $result = $xml->xpath('//europass:learnerinfo/educationlist/education/skills');
      $europass->clearMetadata('educationSkills');
      $europass->educationSkills = fixEncoding($result);
      
      // language
      $result = $xml->xpath('//europass:learnerinfo/languagelist/language[@xsi:type="europass:mother"]/label');
      $europass->motherLanguage = fixEncoding($result[0]);
      $result = $xml->xpath('//europass:learnerinfo/languagelist/language[@xsi:type="europass:foreign"]/label');
      $europass->clearMetadata('foreignLanguages');
      $europass->foreignLanguages = fixEncoding($result);
      
      // skills
      $result = $xml->xpath('//europass:learnerinfo/skilllist/skill');
      $europass->clearMetadata('skills');
      $europass->skills = fixEncoding($result);
      $result = $xml->xpath('//europass:learnerinfo/skilllist/structured-skill/drivinglicence');
      $europass->clearMetadata('drivinglicences');
      $europass->drivinglicences = $result;
    
      // Deal with the file
      $file= new ElggFile();
      $file->owner_guid = $_SESSION['user']->getGUID();
      $file->container_guid = $europass->getGUID();
      $file->setFilename("europass/" . $_SESSION['user']->username . 'cv.xml');
      $file->setMimeType('text/xml');
      $file->open("write");
      $file->write($xmlString);
      $file->close();
      $file->save();
      
      // Keep the file GUID in a europass property
      $europass->file = $file->getGUID();
      
      // Use Europass WebService to get PDF version of the CV
      $client = new SoapClient("http://europass.cedefop.europa.eu/instrumentssrv/services/Instruments?wsdl");
      $content = $client->getDocumentFromCV($xmlString, 'pdf', 'fr_FR');
      
      // Write or overwrite the PDF CV file
      $pdf = new ElggFile();
      $pdf->owner_guid = $_SESSION['user']->getGUID();
      $pdf->container_guid = $europass->getGUID();
      $pdf->setFilename("europass/" . $_SESSION['user']->username . 'cv.pdf');
      $pdf->setMimeType("application/pdf");
      $pdf->open("write");
      $pdf->write($content);
      $pdf->close();
      $pdf->save();
      
      // Keep the file GUID in a europass property
      $europass->PDFfile = $pdf->getGUID();
      
      // Success message
      system_message(elgg_echo("europass:saved"));
      // Remove the xml cache
      unset($_SESSION['xml']);
      // Special forward to top frame
      js_redirect('pg/europass/' . $_SESSION['user']->username);
      // Avoid any automatic forward
      //exit();
    }
  }
  
  // A way to get out of the iFrame context
  function js_redirect($url) {
    global $CONFIG;
    echo '<script type="text/javascript">'
    .'function getgoing(url)'
    .'{'
    .'  top.location = url;'
    .'}'
    .'if (top.frames.length > 0)'
    .'{'
    .'  getgoing("'. $CONFIG->wwwroot . $url .'");'
    .'}'
    .'</script>';
  }

  // This is not a really nice Hack, but the only one I found usefull
  // The Europass XML is returned with strange encoding when used in french
  function fixEncoding($in_str)
  {
    $search = Array("Ã§","ä§","Ã‡","ã‡","Ã©","ä©","Ã‰","ã‰","Ã¨","ä¨","Ãˆ","ãˆ","Ãª","äª","ÃŠ","ãŠ","Ã«","ä«","Ã‹","ã‹","Ã®","ä®","ÃŽ","ãŽ","Ã¯","ä¯","Ã","ã","Ã¬","ã¬","ÃŒ","ãŒ","Ã²","ä²","Ã’","ã’","Ã´","ä´","Ã”","ã”","Ã¶","ä¶","Ã–","ã–","Ãµ","ãµ","Ã•","ã•","Ã³","ã³","Ã“","ã“","Ã¸","ã¸","Ã˜","ã˜","Ã*","ã*","Ã€","ã€","Ã¢","ä¢","Ã‚","ã‚","Ã¤","ä¤","Ã„","ã„","Ã¥","ä¥","Ã…","ã…","Ã»","ã»","Ã›","ã›","Ã¼","ä¼","Ãœ","ãœ","Ã¹","ã¹","Ã™","ã™","ã±","Ã±","Ã‘","ã‘", "Ã ");
    $replace = Array("ç","ç","Ç","Ç","é","é","É","É","è","è","È","È","ê","ê","Ê","Ê","ë","ë","Ë","Ë","î","î","Î","Î","ï","ï","Ï","Ï","ì","ì","Ì","Ì","ò","ò","Ò","Ò","ô","ô","Ô","Ô","ö","ö","Ö","Ö","õ","õ","Õ","Õ","ó","ó","Ó","Ó","ø","ø","Ø","Ø","à","à","À","À","â","â","Â","Â","ä","ä","Ä","Ä","å","å","Å","Å","û","û","Û","Û","ü","ü","Ü","Ü","ù","ù","Ù","Ù","ñ","ñ","Ñ","Ñ","à");
    
    return str_replace($search, $replace, $in_str);
  }  
 ?>